import { queryConfigBykey, saveConfig } from "@/api/config";
import { WEB_INFO_KEY } from "@/constants/configKey.constant";
import { ConfigType } from "@/types/config";
import { message } from "antd";
import { useForm } from "antd/es/form/Form";
import { useState, useCallback, useEffect } from "react";

export type FieldType = {
    name: string;
    url: string;
    logo: string;
    icon: string;
    desc: string;
  };
export const useConfigLink =()=>{
    const [loading, setLoading] = useState(false);
    const [btnLoading, setBtnLoading] = useState(false);
    const [messageApi] = message.useMessage();
    const [form] = useForm();
    const [configInfo, setConfigInfo] = useState<ConfigType.Row<FieldType>>({
      id: "",
      title: "",
      configKey: "",
      config: "",
    });
    const getConfig = useCallback(async () => {
      setLoading(true);
      const res = await queryConfigBykey(WEB_INFO_KEY);
      setLoading(false);
      if (res.code === 200) {
        const obj = res.data || {};
        const config = obj.config ? JSON.parse(obj.config) : {};
        setConfigInfo({
          id: obj.id,
          title: obj.title,
          configKey: obj.configKey,
          config,
        });
  
     
        form.setFieldsValue({
          name: config.name || "",
          icon: config.icon || "",
          logo: config.logo || "",
          desc: config.desc || "",
          url: config.url || "",
        });
      }
    }, [form]);
  
    /**
     * 保存配置
     * @param config
     */
    const saveConfigInf = async (values: FieldType) => {
      const { name, icon,logo ,desc,url} = values;
      const config = {
        name, icon,logo ,desc,url
      };
      const params = {
        id: configInfo?.id,
        configKey: WEB_INFO_KEY,
        config: JSON.stringify(config),
      };
      setBtnLoading(true);
      const res = await saveConfig(params);
      setBtnLoading(false);
      if (res.code === 200) {
        messageApi.success("保存成功");
        getConfig();
      }
    };
    const onFinish = async (values: FieldType) => {
      saveConfigInf(values);
    };
    useEffect(() => {
      getConfig();
    }, [getConfig]);
    return {
        btnLoading,
        form,
        loading,
        onFinish
    }
}